package com.mall.huohuo.aspect.annotation;

import com.mall.huohuo.exception.BusinessException;
import com.mall.huohuo.util.ValidateResult;
import com.mall.huohuo.util.ValidateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * @author zyconding
 * @version AuthParam.java, v 0.1 2020-08-07 16:23 zyconding
 */
@Component
@Aspect
public class ValidateAspect {

    @Pointcut(value = "" +
            "(@within(org.springframework.stereotype.Service)||" +
            "@within(org.springframework.stereotype.Controller)||" +
            "@within(org.springframework.web.bind.annotation.RestController) )&&" +
            "@args(javax.validation.Valid)")
    public void pointcut(){

    }

    @Around(value = "pointcut()")
    public Object handler(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        Object[] args = proceedingJoinPoint.getArgs();
        if (args == null || args.length <= 0) {
            return proceedingJoinPoint.proceed();
        }

        for (Object arg : args) {
            if (arg == null) {
                continue;
            }
            ValidateResult validateResult = ValidateUtil.validate(arg);
            if (!validateResult.isResult()) {
                throw new BusinessException("参数校验：" +validateResult.getParamName()+"【"+ validateResult.getMsg()+"】", 101);
            }
        }

        return proceedingJoinPoint.proceed();
    }
}
